from tools.funciton import write_json_file, read_xlsx_file
import json
import time
from datetime import datetime, timedelta
import random
import string
import os
import pymongo
from config.configs import DINGSTOCK_HOST, DINGSTOCK_PORT, TRADE_URL
from config.configs import DATA_PATH, DOWNLOAD_PATH, DESKTOP_PATH
import requests

# mobile_file = os.path.join(DOWNLOAD_PATH, '用户手机号.xlsx')
# mobile_list = read_xlsx_file(mobile_file, 0)


# def get_user_ids():
#     """获取用户ids"""
#     li = []
#     for i in range(len(mobile_list)):
#         url = f'https://apiv2.dingstock.net/xserver/admin/user/u/page?mobilePhoneNumber={mobile_list[i]}'
#         headers = {
#             'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImxtNGV6a2VvIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNzE2OTc2OTAzfQ.dCgQKmIHQ2MFAk12foFq7d0BIl7RcDL3Wlqsetw6Gu0',
#             'Accept': '*/*',
#             'Host': 'apiv2.dingstock.net',
#             'Connection': 'keep-alive'
#         }
#         r = requests.get(url=url, headers=headers).json()
#         li.append(r['res']['list'][0]['id'])
#     return li

express = pymongo.MongoClient(TRADE_URL).express


def generate_random_string(length):
    # 定义所有可能的字符
    characters = string.ascii_letters + string.digits  # 包含大小写字母和数字
    random_string = ''.join(random.choices(characters, k=length))
    return random_string


def get_timestamp_after_days(days):
    # 获取当前时间
    now = datetime.now()
    # 添加指定的天数
    future_time = now + timedelta(days=days)
    # 转换为时间戳（秒为单位）
    timestamp = time.mktime(future_time.timetuple())
    return int(timestamp) * 1000


def get_usercoupons_file(userIds, couponId, expire_days, num):
    """
    创建指定用户发放券包文件
    :param expire_days 有效天数
    :param num 发放张数
    :param userIds 用户id数组
    :param couponId 发放券包id
    """
    li = []
    file = os.path.join(DATA_PATH, 'user_coupons.json')
    print(express.usercoupons.find_one({}))
    for i in range(len(userIds)):
        for d in range(num):
            param = {
                "_id": generate_random_string(10),
                "userId": userIds[i],
                "couponId": couponId,
                "effectedAt": int(round(time.time() * 1000)),
                "expiredAt": get_timestamp_after_days(expire_days),
                "blocked": False,
                "createdAt": int(round(time.time() * 1000)),
                "updatedAt": int(round(time.time() * 1000)),
                "__v": 0
            }
            li.append(param)
    write_json_file(file=file, data=li)
    express.usercoupons.insert_many(li)


# file = os.path.join(DESKTOP_PATH, '12223.xlsx')
# ids = read_xlsx_file(file, 0)
get_usercoupons_file(["uftRkTV5y2", "tOv6wW6I2T"], 'FS7WR027QJ', 30, 5)